//
import UIKit

//封装OAuth登录接口
class CZUserAccountViewModel: NSObject {
    //单例访问
    static let shareUserAccount: CZUserAccountViewModel = CZUserAccountViewModel()
    //获取用户对象从沙河路径里面读取对象
    var userAccount: CZUserAccount? {
        //解挡用户对象
        return CZUserAccount.loadUserAccount()
    }
    
    //封装判断accessToken是否为nil
    var isLogin: Bool {
        return accessToken != nil
    }

    //判断accessToken的值
    var accessToken: String? {
        guard let token = userAccount?.access_token else {
            return nil
        }
        
        //token一定有值,过期时间大于大于代表没有过期
        let result = userAccount?.expiresDate?.compare(NSDate())
        // 使用降序表示我们从大到小
        if result == NSComparisonResult.OrderedDescending{
            return token
        } else {
            return nil
        }
        
    }
    
    //通过code说去accesstoken
    func requestAccesstoken(code: String,callBack:(isResult:Bool) -> ()) {
        
        CZNetworkTools.sharedToos.requestAccesstoken(code) { (response, error) -> () in
            if error != nil {
               print(error)
                callBack(isResult: false)
                return
            }
            
            //成功的回调
            guard let dict = response as? [String: AnyObject] else {
                print("不是一个正确的json格式")
                callBack(isResult: false)
                return
            }
            
            //执行到这 dic一定有符合我们要求的值
            let userAccount = CZUserAccount(dic: dict)
            print(userAccount)
            //通过accessToken获取用户信息
            self.requestUserInfo(userAccount,callBack:callBack)
            
        }
    }
    
    //获取用户信息
    private func requestUserInfo(userAccount: CZUserAccount,callBack:(isResult:Bool) -> ()){
        
        CZNetworkTools.sharedToos.requestUserInfo(userAccount) { (response, error) -> () in
            if error != nil {
                print(error)
                callBack(isResult: false)
                return
            }
            
            guard let dic = response as? [String: AnyObject] else {
                print("不是一个正确的json文件")
                callBack(isResult: false)
                return
            }
            
            //得到我们的需求的值
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            
            //保存对象
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            //保存用户对象
            let request = userAccount.saveUserAccount()
            
            if request {
                //保存数据成功
                callBack(isResult: true)
                return
                
            } else {
                //失败
                callBack(isResult: false)
                return
            }
        }
    }
   
}























